$(() => {
  let $image = $('#image');
  // 1.2 配置选项
  const option = {
    // 纵横比
    aspectRatio: 400 / 280,
    // 指定预览区域
    preview: '.img-preview',
  };
  fileEvent(option);
  $image.cropper(option);
  let state = '已发布';

  let promise = new Promise(function (resolve, rejected) {
    resolve(getCategory());
  });
  if (location.href.includes('/edit.html')) {
    promise.then(function (res) {
      // $(`[dataid="${cateId}"]`)[0].selected = true;
      // form.render('select');

      async function fn() {
        let arr = location.href.split('?')[1];
        if (!arr) {
          layer.msg('没有获取到要修改的文章!');
          location.href = '/bigevent/article/article.html';
        }
        let id = arr.split('=')[1];
        return $.ajax({
          url: '/my/article/' + id,
          success(res) {
            form.val('articleForm', res.data);
            // cateId = res.data.cate_id;
          },
        });
      }
      fn().then(function (res) {
        initEditor();
      });
    });
  } else {
    initEditor();
  }

  $('.upload').click(function () {
    state = '已发布';
  });
  $('.draft').click(function () {
    state = '草稿';
  });

  $('#articleForm').submit(function (e) {
    e.preventDefault();
    let fd = new FormData(this);
    if (!fd.get('content')) return layer.msg('请输入文章内容', { icon: 5 });
    fd.append('state', state);
    $image
      .cropper('getCroppedCanvas', {
        width: 400,
        height: 280,
      })
      .toBlob(function (blob) {
        let url = '/my/article/add';
        if (fd.get('Id')) {
          url = '/my/article/edit';
        }
        fd.append('cover_img', blob);
        $.ajax({
          url,
          type: 'POST',
          data: fd,
          contentType: false,
          processData: false,
          success(res) {
            layer.msg(res.message);
            if (res.status === 0) {
              location.href = '/bigevent/article/article.html';
            }
          },
        });
      });
  });
});
